// pages/write/write.js
var  uploadTask
Page({

  /**
   * 页面的初始数据
   */
  data: {
    selImgs:[],
    maxlength:6,
    title:'',
    con:'',
    newsrc:[]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
  
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  // onShareAppMessage: function () {
  
  // },

  chooseImg:function(){
    var maxlength = this.data.maxlength,
    that = this;
    if(this.data.selImgs.length>maxlength){
      wx.showModal({
        title: '提示',
        content: '已超出最大选择限制！',
      })
      return false;
    }else{
      console.log(parseInt(maxlength - this.data.selImgs.length));
      wx.chooseImage({
        count: parseInt(maxlength - this.data.selImgs.length), // 默认9
        sizeType: [ 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
        sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
        success: function (res) {
          // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
          var tempFilePaths = res.tempFilePaths;
          if(tempFilePaths.length>0){
            for(var i=0;i<tempFilePaths.length;i++){
              that.data.selImgs.push(tempFilePaths[i]);
            }
          }
          console.log(tempFilePaths);

          


          that.setData({
            selImgs: that.data.selImgs
          });
        }
      })
    }
  },

  close:function(e){
    var idx = e.currentTarget.dataset.idx;
    this.data.selImgs.splice(idx,1);
    console.log(this.data.selImgs);
    this.setData({
      selImgs:this.data.selImgs
    })
  },

  ipttitle:function(e){
    console.log(e.detail.value);
    var title = e.detail.value;
    title = title.replace(/\s/g,"");
    console.log(title);
    this.setData({
      title:title
    })
  },

  iptcon:function(e){
    console.log(e.detail.value);
    var con = e.detail.value;
    con = con.replace(/\s/g, "");
    console.log(con);
    this.setData({
      con:con
    })
  },

  beforeSend:function(){
    var title = this.data.title,
    con = this.data.con,
    that = this;
    
    if(title.length<=0||con.length<=25){
      wx.showModal({
        title: '提示',
        content: '帖子标题或内容不能为空，内容不能少于25字！',
      });
      return false;
    }

    if (this.data.selImgs.length > 0) {
      wx.showLoading({
        title: '正在上传图片...',
        mask:true
      })
      this.uploadImg();
    }else{
      this.send()
    }
  },

  uploadImg:function(){
    var str = new Date(),
    newarr = this.data.newsrc,
    imgarr = this.data.selImgs,
    that = this,
    random = parseInt(Math.random()*10);
    str = "pic" + random + str.getTime();
    if (imgarr.length <= 0){
      wx.showModal({
        title: '提示',
        content: '请选择图片',
      })
      return false;
    }
    if (newarr.length == imgarr.length && newarr.length>0){//选择图片数大于0且都上传成功
      console.log(newarr);
      wx.hideLoading();
      wx.showToast({
        title: '上传成功',
      });
      this.send();
      return false;
    }else{
      var src = imgarr[newarr.length]
    }
    console.log(str);
    uploadTask = wx.uploadFile({
      url: "https://www.meitiannongzi.com/under/app/picture",
      filePath: src,
      name: str,
      header: {
        'content-type': 'multipart/form-data'
      }, // 设置请求的 header
      formData: {
        openid: 12345,
        id: str
      }, // HTTP 请求中其他额外的 form data
      success: function (res) {
        console.log(res);

        if (!!res.data) {
          newarr.push(res.data);
          that.setData({
            newsrc: newarr,
          });
          that.uploadImg();
        } else {
          wx.hideLoading();
          wx.showModal({
            title: '提示',
            content: '获取图片路径失败（uploadFail）',
          })
        }
      },
      fail: function (res) {
        console.log(res);
        wx.hideLoading();
        wx.showModal({
          title: '提示',
          content: '图片生成失败！请稍候重试...',
        })
      }
    });
  },
  send:function(){
    wx.showLoading({
      title: '正在提交...',
      mask:true
    });

    var img = this.data.newsrc||[];
    console.log(img[2])

    wx.request({
      url: 'https://m.nongjike.cn/NJK/app/saveXCartNest',
      method: "POST",
      header: {
        'content-type': "application/x-www-form-urlencoded"
      },
      data:{
        USER_ID:wx.getStorageSync("USER_ID"),
        SUBJECT:this.data.title,
        MESSAGE:this.data.con,
        img1:img[0]||"",
        img2:img[1]||"",
        img3:img[2]||"",
        img4:img[3]||"",
        img5:img[4]||"",
        img6:img[5]||"",
        count:img.length
      },
      success:function(res){
        var data = res.data;
        console.log(data);
        wx.hideLoading();
        if(data.code!=1){
          wx.showModal({
            title: '提示',
            content: data.message,
          });
          return false;
        }else{
          wx.showToast({
            title: '发布成功！',
          });
          setTimeout(function(){
            wx.redirectTo({
              url: '/pages/index/index',
            },3000);
          })
        }
      }
    })

    // setTimeout(function(){
    //   wx.hideLoading();
    //   wx.showToast({
    //     title: '发布成功！',
    //   })
    // },2000);
  }
})